package be.obia.moo.dovebird;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Vector;

import android.util.Log;

public class TCPClient implements Runnable {
    public be.obia.moo.dovebird.MCP.Handler MCP;

	Vector<TCPListener> subscribers = new Vector<TCPListener>(); 
    
	public String Hostname;
	public Integer Port;
	public Boolean keepConnected;
	public Socket socket;
	
	public TCPClient(String hostname, Integer port, TCPListener listener) {
		MCP = new be.obia.moo.dovebird.MCP.Handler((MainActivity) listener);
    	keepConnected = true;
    	Hostname = hostname;
    	Port = port;
    	this.addTCPListener(listener);
	}
	
    private void OnLineReceived(String line){
    	for(int i=0, size = subscribers.size(); i < size; i++)
    		((TCPListener)subscribers.get(i)).lineReceived(new TCPLine(this, line));
    }
    
    public void addTCPListener(TCPListener ensl){
    	subscribers.add(ensl);
    }

    public void removeTCPListener(TCPListener ensl){
    	 subscribers.remove(ensl); 
    }	
    
    public void sendData(String line) {
    	if(this.socket.isConnected()) {
    		TCPLine send = new TCPLine(this, line);
    		send.Send();
    	}
    }
	
	public void run() {
		try {
			InetAddress serverAddr = InetAddress.getByName(Hostname);
			Log.d("TCP", "C: Connecting...");
			socket = new Socket(serverAddr, Port);
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			try {
				while(socket.isConnected() && keepConnected) {
					String line = reader.readLine();
					OnLineReceived(line);
				}
			} finally {
				socket.close();
			}
		} catch (Exception e) {
			Log.e("TCP", "C: Error", e);
		}
	}
}
